package com.wenjiang.Interceptor;

import com.wenjiang.annotation.Required;
import com.wenjiang.config.LanTuPayProperties;
import com.wenjiang.enums.LanTuPayErrorEnum;
import com.wenjiang.exception.LanTuPayException;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * <p>
 * 必填参数拦截
 * </p>
 *
 * @author lwj
 * @since 2024/11/29.
 */


@Slf4j
public class HttpRequestRequiredInterceptor extends AbstractInterceptor {


    public HttpRequestRequiredInterceptor(LanTuPayProperties lanTuPayProperties) {
        super(lanTuPayProperties);
    }

    @Override
    @SneakyThrows
    public Object requestInterceptor(Object request) {
        Class<?> requestClass = request.getClass();
        //获取request 对象上的 属性
        Field[] declaredFields = requestClass.getDeclaredFields();
        //获取属性上的注解
        for (Field field : declaredFields) {
            field.setAccessible(Boolean.TRUE);
            Required annotation = field.getAnnotation(Required.class);
            if (annotation != null) {
                Object o = field.get(request);
                if (o == null) {
                    if (StringUtils.isNotBlank(annotation.message())) {
                        throw new LanTuPayException(LanTuPayErrorEnum.INVALID_PARAMETERS.getCode(), LanTuPayErrorEnum.INVALID_PARAMETERS.getMessage());
                    } else {
                        log.error("属性field:{} 未填写值",field.getName());
                        throw new LanTuPayException(LanTuPayErrorEnum.INVALID_PARAMETERS.getCode(), annotation.message());
                    }
                }
            }
        }

        // 交给下个节点
        HttpInterceptor nextHttpRequestInterceptor = next();
        if (nextHttpRequestInterceptor == null){
            return request;
        }
        return  nextHttpRequestInterceptor.requestInterceptor(request);
    }

    @Override
    public Boolean isSupport(Object request) {
        return Boolean.TRUE;
    }

}
